<template>
  <div class="app-container form">
    <h3 class="form-tit">{{topicName}}</h3>
<!--    <editor v-model="content" style="border-bottom:1px solid #f1e8e8;margin: 0 17.5px 10px;padding-bottom: 10px;"></editor>-->
    <el-form ref="form" :model="formData" label-width="80px" :rules="rules">
      <el-form-item v-for="(item,index) in formList" :prop="item.vModel" :label="item.label">
        <el-input v-if="item.itemType == 'one-line-text'" v-model="formData[`${item.vModel}`]" :placeholder="item.placeholder" :clearable="item.clearable" :style="{width: '100%'}" :readonly="type=='view'">
        </el-input>
        <el-input v-if="item.itemType == 'lines-text'"  type="textarea" v-model="formData[`${item.vModel}`]" :placeholder="item.placeholder"  :clearable="item.clearable"  :style="{width: '100%'}"  :readonly="type=='view'">
        </el-input>
        <el-input v-if="item.itemType == 'pass-word'" v-model="formData[`${item.vModel}`]" show-password :placeholder="item.placeholder"  :clearable="item.clearable"  :style="{width: '100%'}" :readonly="type=='view'">
        </el-input>
        <el-input-number v-if="item.itemType == 'counter'" v-model="formData[`${item.vModel}`]" show-password :placeholder="item.placeholder"  :clearable="item.clearable"  :style="{width: '100%'}" :readonly="type=='view'">
        </el-input-number>
        <el-select v-if="item.itemType == 'drop-down'" v-model="formData[`${item.vModel}`]" :placeholder="item.placeholder" :clearable="item.clearable" :style="{width: '100%'}" :readonly="type=='view'" :disabled="type=='view'">
          <el-option v-for="(self, index) in item['options']" :key="index" :label="self.label"
                     :value="self.label" :disabled="self.disabled"></el-option>
        </el-select>
        <el-cascader v-if="item.itemType == 'cascade-selection'" v-model="formData[`${item.vModel}`]" :options="item['options']"
                     :style="{width: '100%'}" :placeholder="item.placeholder"  :clearable="item.clearable" :readonly="type=='view'"></el-cascader>
        <el-radio-group v-if="item.itemType == 'radio'" v-model="formData[`${item.vModel}`]">
          <el-radio v-for="(one, index) in item['options']" :key="index" :label="one.label"
                    :disabled="item.disabled" :readonly="type=='view'">{{one.label}}</el-radio>
        </el-radio-group>
        <!--        <el-checkbox-group v-if="item.itemType == 'multiple-choice'" v-model="formData[`${item.vModel}`]">-->
        <!--          <el-checkbox v-for="(self, index) in item['options']" :key="index" :label="self.value"-->
        <!--                       :disabled="item.disabled">{{self.label}}</el-checkbox>-->
        <!--        </el-checkbox-group>-->
        <el-checkbox-group  v-if="item.itemType == 'multiple-choice'" v-model="multiple">
          <el-checkbox v-for="(self, index) in item['options']" :key="index" :label="self.label"
                       :disabled="item.disabled"  :readonly="type=='view'">{{self.label}}</el-checkbox>
        </el-checkbox-group>
        <el-switch v-if="item.itemType == 'switch'" v-model="formData[`${item.vModel}`]" :readonly="type=='view'"></el-switch>
        <!--        <el-slider v-if="item.itemType == 'slider'" v-model="formData[`${item.vModel}`]" :max='100' :step='1'></el-slider>-->
        <el-time-picker v-if="item.itemType == 'time-picker'" v-model="formData[`${item.vModel}`]" format="HH:mm:ss" value-format="HH:mm:ss"
                        :picker-options='{"selectableRange":"00:00:00-23:59:59"}' :style="{width: '100%'}"
                        :placeholder="item.placeholder"  :clearable="item.clearable" :readonly="type=='view'"></el-time-picker>
        <el-time-picker v-if="item.itemType == 'range-time-picker'" v-model="formData[`${item.vModel}`]" is-range format="HH:mm:ss" value-format="HH:mm:ss"
                        :style="{width: '100%'}" start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至"
                        :clearable="item.clearable" :readonly="type=='view'"></el-time-picker>
        <el-date-picker v-if="item.itemType == 'date-picker'" v-model="formData[`${item.vModel}`]" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                        :style="{width: '100%'}" :placeholder="item.placeholder"  :clearable="item.clearable" :readonly="type=='view'"></el-date-picker>
        <el-date-picker v-if="item.itemType == 'range-date-picker'" v-model="formData[`${item.vModel}`]" type="daterange" format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd" :style="{width: '100%'}" start-placeholder="开始日期" end-placeholder="结束日期"
                        range-separator="至"  :clearable="item.clearable" :readonly="type=='view'"></el-date-picker>
        <el-rate  v-if="item.itemType == 'score'" v-model="formData[`${item.vModel}`]" ></el-rate>
        <el-color-picker v-if="item.itemType == 'color-selection'" v-model="formData[`${item.vModel}`]" size="medium" :readonly="type=='view'"></el-color-picker>
        <el-upload
          :disabled="type=='view'"
          v-if="item.itemType == 'upload'"
          :action="fieldAction"
          list-type="picture-card"
          :file-list="formData[`${item.vModel}`]"
          accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.PBG,.GIF"
          :on-preview="handlePictureCardPreview">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button v-if="type!='view'" type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="back">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { formDetail,addData } from "@/api/form.js";
export default {
  name: "formview",
  data() {
    return {
      formData:{},
      detail:{},
      formList:[],
      id:'',
      topicName:'',
      content:'',
      type:'',
      itemType:'',
      rules: {},
      multiple:'',

      fieldAction:'/dev-api/common/upload',
      dialogImageUrl: '',
      dialogVisible: false,
      picFeild:'',

      designVa(obj){
        return (rule, value, callback) => {
          if ((!value & value !== 0) || value === '') {
            callback();
            return;
          }
          let reg = obj.reg;
          if (reg.test(value)) {
            callback();
          } else {
            callback(new Error(obj.info));
          }
        };
      },
    };
  },
  mounted() {
    this.id = this.$route.query.id
    this.topicName = this.$route.query.topicName
    this.type = this.$route.query.type
    this.formData = JSON.parse(this.$route.query.formData)

    Object.keys(this.formData).forEach((key)=>{
      if( this.formData[key].substr(0,1) == '[' ){
        this.formData[key] = JSON.parse(this.formData[key])
      }
    })
    this.getDetail()
  },
  methods: {
    onSubmit(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          let temp = []
          Object.keys(this.formData).forEach((key,index)=>{
            temp.push( {[key]: this.formData[key] } )
          })
          let tableValue = JSON.stringify(temp)
          addData({topicId:this.id,tableValue:tableValue} ).then(response => {
            this.$modal.msgSuccess("提交成功");
            this.$refs["form"].clearValidate()
            //this.$router.push({path:'/datalist',query:{topicId:this.id}})
          });
        }
      });
    },
    getDetail(){
      formDetail(this.id).then((res)=>{
        let temp
        this.content = res.data.content
        temp = res.data.tableAttributeList
        console.log(temp)

        temp.forEach((item=>{
          if(item.clearable == '1'){
            item.clearable = true
          }else{
            item.clearable = false
          }
          if(item.required == '1'){
            item.required = true
          }else{
            item.required = false
          }
          if(item.disabled == '1'){
            item.disabled = true
          }else{
            item.disabled = false
          }
          if(item.changeTag == '1'){
            item.changeTag = true
          }else{
            item.changeTag = false
          }

          Object.keys(item).forEach((key)=>{
            if( key == 'style' || key == 'options' || key == 'regList'){
              if(item[key]){
                item[key] = JSON.parse(item[key])
              }
            }
            if( key == 'regList' && item.regList && item.regList.length > 0){

              this.$set(this.rules,`${item.vModel}`,[])
              item.regList.forEach(one=>{
                Object.keys(one).forEach(oneKey=>{
                  if(oneKey=='max'){
                    this.rules[`${item.vModel}`].push({'max':one.max,'message':one.message})
                  }
                  if(oneKey=='pattern'){
                    this.rules[`${item.vModel}`].push({validator:this.designVa({reg:eval(one.pattern),info:one.message}) })
                  }
                })
              })
            }
          })
        }))
        this.formList = temp.filter((item)=>{
          return item.itemType != 'slider'
        })
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    back(){
      this.$router.go(-1);
    }
  },
  watch:{
    rules:{
      handler(val){
        return val
      },
      deep:true
    }
  }
};
</script>
<style scoped>
.app-container{
  padding:10px !important
}
.form-tit{
  margin: 0 0 20px 0;
  border-bottom: 2px solid #eee;
  text-align: center;
  color: #333;
  font-weight: bold;
  background: #f7f7f7;
  line-height: 40px;
}
.form >>> .el-checkbox-group,
.form >>> .el-radio-group{
  display:flex;
  flex-direction: column;
}
.form >>> .el-radio{
  height: 36px;
  align-items: center;
  display: flex;
}
.content >>> img{
  max-width:100% !important;
  height:auto;
}
</style>
